/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package canteen.sys.view;

import canteen.sys.model.entity.Author;
import canteen.sys.model.entity.Item;
import canteen.sys.model.entity.Languages;
import canteen.sys.model.entity.Owner;
import canteen.sys.model.entity.OwnerItem;
import canteen.sys.model.entity.StatusOfUse;
import canteen.sys.model.entity.Store;
import canteen.sys.model.entity.TypeOfRegulation;
import canteen.sys.model.entity.TypeOfUse;
import canteen.sys.model.generic.HibernateDAOFactory;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import org.hibernate.HibernateException;

/**
 *
 * @author TNT
 */
public class ItemM extends javax.swing.JInternalFrame implements ActionView<Item> {

    HibernateDAOFactory hibernateDAOFactory = HibernateDAOFactory.getInstance();
    DefaultTableModel modelTableItem;
    List<Item> listItem;

    /**
     * Creates new form StoreM
     */
    public ItemM() {
        initComponents();
        showAllCombobox();
        modelTableItem = (DefaultTableModel) tbitem.getModel();
        txtmodifiedDate.setText(new SimpleDateFormat("yyyy - MM - dd")
                .format(new java.util.Date()));
        listItem = hibernateDAOFactory.getItemDAO().findAllByStatus(true);
        showList(listItem);
        listSelectionListener();
        listenerTableModel();
    }

    private void showAllCombobox() {

        List<Languages> listLanguage = hibernateDAOFactory
                .getLanguageDAO().findAllByStatus(true);
        List<Author> listAuthor = hibernateDAOFactory
                .getAuthorDAO().findAllByStatus(true);
        List<Owner> listOwner = hibernateDAOFactory
                .getOwnerDAO().findAllByStatus(true);
        List<OwnerItem> listOwnerItems = null;
        List<Store> listStore = hibernateDAOFactory
                .getStoreDAO().findAllByStatus(true);
        List<TypeOfUse> listItemTnt = hibernateDAOFactory
                .getTypeOfUseDAO().findAllByStatus(true);
        List<TypeOfRegulation> listTypeOfRegulation = hibernateDAOFactory
                .getTypeOfRegulationDAO().findAllByStatus(true);
        List<StatusOfUse> listStatusOfuse = hibernateDAOFactory
                .getStatusOfUserDAO().findAllByStatus(true);
        if (listAuthor.isEmpty() || listLanguage.isEmpty()
                || listOwner.isEmpty() || listStatusOfuse.isEmpty()
                || listStore.isEmpty() || listTypeOfRegulation.isEmpty()
                || listItemTnt.isEmpty()) {
            btaddnew.setEnabled(false);
            btrefresh.setEnabled(false);
            btdelete.setEnabled(false);
        } else {
            btaddnew.setEnabled(true);
            btrefresh.setEnabled(true);
        }
        //language
        if (listLanguage.size() > 0) {
            for (Languages languages : listLanguage) {
                ComboboxRecInfo<Languages> combobox = new ComboboxRecInfo<>();
                combobox.setName(languages.getName());
                combobox.setKeyData(languages);
                cblanguage.addItem(combobox);
            }
        }
        if (listAuthor.size() > 0) {
            for (Author author : listAuthor) {
                ComboboxRecInfo<Author> combobox = new ComboboxRecInfo<>();
                combobox.setName(author.getName());
                combobox.setKeyData(author);
                cbauthor.addItem(combobox);
            }
        }
        if (listOwner.size() > 0) {
            for (Owner owner : listOwner) {
                ComboboxRecInfo<Owner> combobox = new ComboboxRecInfo<>();
                combobox.setName(owner.getName());
                combobox.setKeyData(owner);
                cbowner.addItem(combobox);
            }
        }

        ComboboxRecInfo<Owner> comboboxOwner =
                (ComboboxRecInfo<Owner>) cbowner.getSelectedItem();
        if (comboboxOwner != null) {
            listOwnerItems = hibernateDAOFactory
                    .getOwnerItemDAO()
                    .findAllByProByNameAndStatus("ownerId",
                    comboboxOwner.getKeyData().getOwnerId(), true);
        }
        if (listOwnerItems.isEmpty()) {
            btaddnew.setEnabled(false);
            btrefresh.setEnabled(false);
            btdelete.setEnabled(false);

        } else if (listOwnerItems.size() > 0) {
            for (OwnerItem owner : listOwnerItems) {
                ComboboxRecInfo<OwnerItem> combobox = new ComboboxRecInfo<>();
                combobox.setName(owner.getNameOfOwner());
                combobox.setKeyData(owner);
                cbOwnerItem.addItem(combobox);
            }
            btaddnew.setEnabled(true);
            btrefresh.setEnabled(true);
        }
        if (listStore.size() > 0) {
            for (Store store : listStore) {
                ComboboxRecInfo<Store> combobox = new ComboboxRecInfo<>();
                combobox.setName(store.getName());
                combobox.setKeyData(store);
                cbstore.addItem(combobox);
            }
        }
        if (listItemTnt.size() > 0) {
            for (TypeOfUse typeOfUse : listItemTnt) {
                ComboboxRecInfo<TypeOfUse> combobox = new ComboboxRecInfo<>();
                combobox.setName(typeOfUse.getName());
                combobox.setKeyData(typeOfUse);
                cbtypeofuse.addItem(combobox);
            }
        }
        if (listTypeOfRegulation.size() > 0) {
            for (TypeOfRegulation typeOfRegulation : listTypeOfRegulation) {
                ComboboxRecInfo<TypeOfRegulation> combobox = new ComboboxRecInfo<>();
                combobox.setName(typeOfRegulation.getName());
                combobox.setKeyData(typeOfRegulation);
                cbtypeofregulation.addItem(combobox);
            }
        }
        if (listStatusOfuse.size() > 0) {
            for (StatusOfUse item : listStatusOfuse) {
                ComboboxRecInfo<StatusOfUse> combobox = new ComboboxRecInfo<>();
                combobox.setName(item.getName());
                combobox.setKeyData(item);
                cbstatusofuse.addItem(combobox);
            }
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tbitem = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        txtcode = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtothercode = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        cbpublishdate = new org.freixas.jcalendar.JCalendarCombo();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        cbauthor = new javax.swing.JComboBox();
        cblanguage = new javax.swing.JComboBox();
        cbowner = new javax.swing.JComboBox();
        cbstore = new javax.swing.JComboBox();
        cbtypeofuse = new javax.swing.JComboBox();
        cbstatusofuse = new javax.swing.JComboBox();
        rbstatus = new javax.swing.JRadioButton();
        jLabel12 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        txtname = new javax.swing.JTextField();
        cbsearch = new javax.swing.JComboBox();
        btsearch = new javax.swing.JButton();
        txtsearch = new javax.swing.JTextField();
        cbtypeofregulation = new javax.swing.JComboBox();
        jLabel14 = new javax.swing.JLabel();
        jLabel15 = new javax.swing.JLabel();
        txtmodifiedDate = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtnote = new javax.swing.JTextArea();
        jLabel16 = new javax.swing.JLabel();
        btaddnew = new javax.swing.JButton();
        btrefresh = new javax.swing.JButton();
        btdelete = new javax.swing.JButton();
        txtVersion = new javax.swing.JSpinner();
        cbstatus = new javax.swing.JComboBox();
        txtTotalPage = new javax.swing.JSpinner();
        cbOwnerItem = new javax.swing.JComboBox();

        setClosable(true);
        setTitle("Tài liệu");

        tbitem.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Số đăng ký", "Tên tác phẩm", "Tác giả", "Trạng thái"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tbitem);
        tbitem.getColumnModel().getColumn(0).setMaxWidth(100);
        tbitem.getColumnModel().getColumn(3).setMaxWidth(100);

        jLabel1.setText("Số đăng ký");

        txtcode.setEditable(false);

        jLabel2.setText("Số đăng ký khác");

        jLabel3.setText("Số trang");

        jLabel4.setText("Ngày xuất bản");

        cbpublishdate.setDateFormat(new SimpleDateFormat("yyyy - MM - dd"));

        jLabel5.setText("Lần xuất bản");

        jLabel6.setText("Tác giả");

        jLabel7.setText("Ngôn ngữ");

        jLabel8.setText("Chủ sở hữu");

        jLabel9.setText("Nơi lưu trữ");

        jLabel10.setText("Đơn vị sử dụng");

        jLabel11.setText("PP sử dụng");

        cbowner.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbownerActionPerformed(evt);
            }
        });

        rbstatus.setSelected(true);

        jLabel12.setText("Trạng thái");

        jLabel13.setText("Tên tài liệu");

        txtname.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtnameKeyReleased(evt);
            }
        });

        cbsearch.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Tất cả", "Tác giả", "Ngôn ngữ", "Chủ sở hữu", "Nơi lưu trữ", "Đơn vị sử dụng", "PP sử dụng", "Thỏa thuận" }));
        cbsearch.setToolTipText("");

        btsearch.setText("Search");
        btsearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btsearchActionPerformed(evt);
            }
        });

        jLabel14.setText("Thỏa thuận");

        jLabel15.setText("Lần sửa cuối");

        txtmodifiedDate.setEditable(false);
        txtmodifiedDate.setText("10/26/2012");

        txtnote.setColumns(20);
        txtnote.setRows(5);
        jScrollPane2.setViewportView(txtnote);

        jLabel16.setText("Chú thích");

        btaddnew.setText("Thêm mới");
        btaddnew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btaddnewActionPerformed(evt);
            }
        });

        btrefresh.setText("Làm mới");
        btrefresh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btrefreshActionPerformed(evt);
            }
        });

        btdelete.setText("Xóa");
        btdelete.setEnabled(false);
        btdelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btdeleteActionPerformed(evt);
            }
        });

        txtVersion.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtVersionKeyReleased(evt);
            }
        });

        cbstatus.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Hiện", "Ẩn" }));
        cbstatus.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbstatusActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 73, Short.MAX_VALUE))
                                .addGap(29, 29, 29)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(cbpublishdate, javax.swing.GroupLayout.PREFERRED_SIZE, 158, Short.MAX_VALUE)
                                    .addComponent(txtTotalPage)
                                    .addComponent(txtVersion, javax.swing.GroupLayout.Alignment.LEADING)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btaddnew, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(btrefresh, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(29, 29, 29)
                                .addComponent(btdelete, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(37, 37, 37))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(14, 14, 14)
                                        .addComponent(txtname))
                                    .addGroup(layout.createSequentialGroup()
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(txtcode, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(txtothercode, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE))))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel15)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel7)
                                    .addComponent(jLabel8)
                                    .addComponent(jLabel9)
                                    .addComponent(jLabel10)
                                    .addComponent(jLabel11)
                                    .addComponent(jLabel12)
                                    .addComponent(jLabel14)
                                    .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(29, 29, 29)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(rbstatus)
                                        .addGap(0, 0, Short.MAX_VALUE))
                                    .addComponent(cbstore, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(cbtypeofuse, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(cbstatusofuse, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(cbtypeofregulation, 0, 158, Short.MAX_VALUE)
                                    .addComponent(txtmodifiedDate)
                                    .addComponent(cbauthor, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(cbowner, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(cblanguage, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cbOwnerItem, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 555, Short.MAX_VALUE)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(txtsearch)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(cbstatus, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(cbsearch, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(btsearch))
                        .addComponent(jScrollPane2))
                    .addComponent(jLabel16))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(txtothercode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtcode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cbsearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btsearch)
                    .addComponent(txtsearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cbstatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 336, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel16))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(6, 6, 6)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel13))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(txtTotalPage, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(cbpublishdate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(7, 7, 7)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(txtVersion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(cblanguage, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel7))
                                .addGap(6, 6, 6)
                                .addComponent(cbauthor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jLabel6))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel8)
                            .addComponent(cbowner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cbOwnerItem, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(6, 6, 6)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel9)
                            .addComponent(cbstore, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel10)
                            .addComponent(cbtypeofuse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cbstatusofuse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel11))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(cbtypeofregulation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel14))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel12, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(rbstatus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(4, 4, 4)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel15)
                            .addComponent(txtmodifiedDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(btaddnew)
                        .addComponent(btrefresh)
                        .addComponent(btdelete)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btaddnewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btaddnewActionPerformed
        // TODO add your handling code here:
        try {
            Item item = new Item();
            if (btaddnew.getText().equals("Thêm mới")) {
                setItem(item);
                validInsertItem(item);
            } else {
                int selectedIndex = tbitem.getSelectedRow();
                if (selectedIndex != -1) {
                    item = listItem.get(listItem
                            .size() - 1 - selectedIndex);
                    setItem(item);
                    validInsertItem(item);
                    btaddnew.setText("Thêm mới");
                    btrefresh.setText("Làm mới");
                }
            }
            this.txtname.requestFocus();
        } catch (HibernateException ex) {
            JOptionPane.showMessageDialog(this,
                    "Thêm mới Sách,Tạp Chí lỗi!\n Lỗi: " + ex.getMessage(),
                    "Lỗi", JOptionPane.ERROR_MESSAGE);
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this,
                    "Số lượng trang nhập phải là số!\n Lỗi: " + ex.getMessage(),
                    "Lỗi", JOptionPane.ERROR_MESSAGE);
        }
        txtname.selectAll();
        rbstatus.setSelected(true);
    }//GEN-LAST:event_btaddnewActionPerformed

    private void btrefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btrefreshActionPerformed
        // TODO add your handling code here:
        if (btrefresh.getText().equals("Làm mới")) {
            txtname.setText("");
            txtVersion.setValue(0);
            txtcode.setText("");
            txtmodifiedDate.setText(new SimpleDateFormat("yyyy - MM - dd")
                    .format(new java.util.Date()));
            txtnote.setText("");
            txtothercode.setText("");
            txtTotalPage.setValue(0);
        } else {
            clearAll();
        }
    }//GEN-LAST:event_btrefreshActionPerformed

    private void btdeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btdeleteActionPerformed
        // TODO add your handling code here:
        if (JOptionPane.showConfirmDialog(this, "Bạn có chắc chắn?", "Cảnh báo",
                JOptionPane.WARNING_MESSAGE) == JOptionPane.OK_OPTION) {
            try {
                if (tbitem.getSelectedRow() != -1) {
                    int indexList = listItem.size() - 1 - tbitem.getSelectedRow();
                    Item item = listItem.get(indexList);
                    deleteRow(tbitem.getSelectedRow());
                    hibernateDAOFactory.getItemDAO().makeTransient(item);
                    clearAll();
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "Không thể xóa được, "
                        + "Sách này đã được sử dụng!\n");
            }
        }
    }//GEN-LAST:event_btdeleteActionPerformed

    private void cbstatusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbstatusActionPerformed
        // TODO add your handling code here:
        clearAll();
        if (listItem != null) {
            listItem.clear();
        }
        boolean status = false;
        if (cbstatus.getSelectedIndex() == 0) {
            status = true;
        }
        listItem = hibernateDAOFactory.getItemDAO().findAllByStatus(status);
        showList(listItem);
    }//GEN-LAST:event_cbstatusActionPerformed

    private void cbownerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbownerActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cbownerActionPerformed

    private void txtnameKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtnameKeyReleased
        // TODO add your handling code here:
        txtcode.setText(generateCode(txtname.getText()));
        txtothercode.setText(generateCode(txtname.getText()));
    }//GEN-LAST:event_txtnameKeyReleased

    private void txtVersionKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtVersionKeyReleased
        // TODO add your handling code here:
        txtcode.setText(generateCode(txtname.getText()));
        txtothercode.setText(generateCode(txtname.getText()));
    }//GEN-LAST:event_txtVersionKeyReleased

    private void btsearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btsearchActionPerformed
        // TODO add your handling code here:
        boolean status = false;
        String wordSearch = txtsearch.getText();
        if (cbstatus.getSelectedIndex() == 0) {
            status = true;
        }
        if (cbsearch.getSelectedIndex() == 0) {
            listItem.clear();
            listItem = hibernateDAOFactory.getItemDAO().findAllByNameAndStatus(wordSearch, status);
        } else if (cbsearch.getSelectedIndex() == 1) {
            //Tac gia
            listItem.clear();
            listItem = hibernateDAOFactory.getItemDAO().findAllItemByAuthor(wordSearch, status);
        } else if (cbsearch.getSelectedIndex() == 2) {
            //Ngon ngu
            listItem.clear();
            listItem = hibernateDAOFactory.getItemDAO().findAllItemByLanguage(wordSearch, status);
        } else if (cbsearch.getSelectedIndex() == 3) {
            //Chu so huu
            listItem.clear();
            listItem = hibernateDAOFactory.getItemDAO().findAllItemByOwner(wordSearch, status);
        } else if (cbsearch.getSelectedIndex() == 4) {
            //Noi luu chu
            listItem.clear();
            listItem = hibernateDAOFactory.getItemDAO().findAllItemByStore(wordSearch, true, status);
        } else if (cbsearch.getSelectedIndex() == 5) {
            //Don vi su dung
            listItem.clear();
            listItem = hibernateDAOFactory.getItemDAO().findAllItemByTypeOfUse(wordSearch, status);
        } else if (cbsearch.getSelectedIndex() == 6) {
            //Phuong phap su dung
            listItem.clear();
            listItem = hibernateDAOFactory.getItemDAO().findAllItemByStatusOfUse(wordSearch, status);
        } else if (cbsearch.getSelectedIndex() == 7) {
            //Thoa thuan
            listItem.clear();
            listItem = hibernateDAOFactory.getItemDAO().findAllItemByTypeOfRegulation(wordSearch, status);
        }
        showList(listItem);
    }//GEN-LAST:event_btsearchActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btaddnew;
    private javax.swing.JButton btdelete;
    private javax.swing.JButton btrefresh;
    private javax.swing.JButton btsearch;
    private javax.swing.JComboBox cbOwnerItem;
    private javax.swing.JComboBox cbauthor;
    private javax.swing.JComboBox cblanguage;
    private javax.swing.JComboBox cbowner;
    private org.freixas.jcalendar.JCalendarCombo cbpublishdate;
    private javax.swing.JComboBox cbsearch;
    private javax.swing.JComboBox cbstatus;
    private javax.swing.JComboBox cbstatusofuse;
    private javax.swing.JComboBox cbstore;
    private javax.swing.JComboBox cbtypeofregulation;
    private javax.swing.JComboBox cbtypeofuse;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JRadioButton rbstatus;
    private javax.swing.JTable tbitem;
    private javax.swing.JSpinner txtTotalPage;
    private javax.swing.JSpinner txtVersion;
    private javax.swing.JTextField txtcode;
    private javax.swing.JTextField txtmodifiedDate;
    private javax.swing.JTextField txtname;
    private javax.swing.JTextArea txtnote;
    private javax.swing.JTextField txtothercode;
    private javax.swing.JTextField txtsearch;
    // End of variables declaration//GEN-END:variables

    @Override
    public void deleteRow(int index) {
        if (modelTableItem.getRowCount() > 0) {
            if (index > 0) {
                tbitem.setRowSelectionInterval(index - 1, index - 1);
                modelTableItem.removeRow(index);
            } else {
                tbitem.setRowSelectionInterval(index + 1, index + 1);
                modelTableItem.removeRow(0);
            }
        } else {
            JOptionPane.showMessageDialog(this, "Không có dòng nào để xóa!",
                    "Cảnh báo!", JOptionPane.WARNING_MESSAGE);
        }
    }

    @Override
    public void updateRow(Item row, int index) {
        modelTableItem.setValueAt(row.getOtherCode(), index, 0);
        modelTableItem.setValueAt(row.getName(), index, 1);
        modelTableItem.setValueAt(row.getAuthor().getName(), index, 2);
        if (row.isStatus()) {
            modelTableItem.setValueAt("Hiện", index, 3);
        } else {
            modelTableItem.setValueAt("Ẩn", index, 3);
        }
    }

    @Override
    public void addRow(Item row, boolean posion) {
        String status = "Hiện";
        if (!row.isStatus()) {
            status = "Ẩn";
        }
        if (posion) {
            modelTableItem.insertRow(0, new Object[]{row.getOtherCode() + "",
                        row.getName(), row.getAuthor().getName(), status});
        } else {
            modelTableItem.insertRow(tbitem.getRowCount(),
                    new Object[]{row.getOtherCode() + "",
                        row.getName(), row.getAuthor().getName(), status});
        }
        listItem.add(row);
    }

    @Override
    public final void showList(List<Item> list) {
        String status;
        int totalrow = tbitem.getRowCount();
        if (totalrow > 0) {
            for (int i = 0; i < totalrow; i++) {
                modelTableItem.removeRow(0);
            }
        }
        if (list != null && list.size() > 0) {
            for (Item item : list) {
                if (item.isStatus()) {
                    status = "Hiện";
                } else {
                    status = "Ẩn";
                }
                modelTableItem.insertRow(0, new Object[]{item.getOtherCode() + "",
                            item.getName(), item.getAuthor().getName(), status});
            }
        }
    }

    @Override
    public void showDetail(Item object) {
        try {
            txtVersion.setValue(object.getVersion());
            txtcode.setText(object.getCode());
            txtmodifiedDate.setText(object.getModifiedDate().toString());
            txtname.setText(object.getName());
            txtnote.setText(object.getNote());
            txtothercode.setText(object.getOtherCode());
            txtTotalPage.setValue(object.getTotalPage());
            cbauthor.setSelectedItem(object.getAuthor().getName());
            cblanguage.setSelectedItem(object.getLanguage().getName());
            cbowner.setSelectedItem(object.getOwnerItem().getNameOfOwner());
            cbpublishdate.setDate(object.getPublishDate());
            cbstatusofuse.setSelectedItem(object.getStatusOfUse().getName());
            cbstore.setSelectedItem(object.getStore().getName());
            cbtypeofregulation.setSelectedItem(object.getTypeOfRegulation().getName());
            cbtypeofuse.setSelectedItem(object.getTypeOfUse().getName());
            rbstatus.setSelected(object.isStatus());
        } catch (Exception ex) {
        }
    }

    @Override
    public Item getObject(int index) {
        Item author = new Item();
        try {
            if (listItem != null && listItem.size() > 0 && cbstatus.isFocusOwner() == false) {
                int indexOfList = listItem.size() - 1 - index;
                author = listItem.get(indexOfList);
            }
        } catch (ArrayIndexOutOfBoundsException ex) {
        } catch (IndexOutOfBoundsException ex) {
        }
        return author;
    }

    @Override
    public void setObject(Item object) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public boolean validObject(Item object) {
        if (object.getName().equals("") || object.getName() == null) {
            JOptionPane.showMessageDialog(this, "Tên Sách chưa được nhập!");
            return false;
        }
        if (object.getCode().equals("") || object.getCode() == null) {
            JOptionPane.showMessageDialog(this, "Mã lỗi chưa được nhập!");
            return false;
        }
        return true;
    }

    public final void listSelectionListener() {
        tbitem.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                int rowSelected = tbitem.getSelectedRow();
                showDetail(getObject(rowSelected));
                btaddnew.setText("Sửa");
                btrefresh.setText("Hủy");
                btdelete.setEnabled(true);
            }
        });
    }

    public final void listenerTableModel() {
        modelTableItem.addTableModelListener(new TableModelListener() {
            @Override
            public void tableChanged(TableModelEvent e) {
                if (e.getType() == TableModelEvent.DELETE
                        && cbstatus.isFocusOwner() == false
                        && btsearch.isFocusOwner() == false) {
                    JOptionPane.showMessageDialog(null, "Xóa thành công!");
                } else if (e.getType() == TableModelEvent.INSERT
                        && cbstatus.isFocusOwner() == false
                        && btsearch.isFocusOwner() == false) {
                    JOptionPane.showMessageDialog(null, "Thêm Sách thành công!");
                } else if (e.getType() == TableModelEvent.UPDATE
                        && e.getColumn() == 1
                        && cbstatus.isFocusOwner() == false
                        && btsearch.isFocusOwner() == false) {
                    JOptionPane.showMessageDialog(null, "Sửa Sách thành công!");
                }
            }
        });
    }

    private void validInsertItem(Item item) {
        if (validObject(item)) {
            Item itemResult = hibernateDAOFactory.getItemDAO().makePersistent(item);
            showDetail(itemResult);
            if (btaddnew.getText().equals("Thêm mới")) {
                addRow(item, true);
            } else {
                updateRow(item, tbitem.getSelectedRow());
            }
        }
    }

    @SuppressWarnings("empty-statement")
    private void setItem(Item item) throws NumberFormatException {
        item.setCode(txtothercode.getText());
        item.setOtherCode(txtothercode.getText());
        item.setName(txtname.getText());
        item.setTotalPage(Integer.parseInt(txtTotalPage.getValue().toString()));
        item.setPublishDate(new Date(cbpublishdate.getCalendar()
                .getInstance().getTimeInMillis()));
        item.setVersion(Integer.parseInt(txtVersion.getValue().toString()));
        item.setNote(txtnote.getText());
        item.setStatus(rbstatus.isSelected());
        item.setModifiedDate(new java.sql.Date(Calendar
                .getInstance().getTimeInMillis()));
        item.setStatus(rbstatus.isSelected());
        //------------------------------------
        ComboboxRecInfo<Languages> comboLanguage = (ComboboxRecInfo<Languages>) cblanguage
                .getSelectedItem();
        ComboboxRecInfo<Author> comboAuthor = (ComboboxRecInfo<Author>) cbauthor
                .getSelectedItem();
        ComboboxRecInfo<OwnerItem> comboOwner = (ComboboxRecInfo<OwnerItem>) cbOwnerItem
                .getSelectedItem();
        ComboboxRecInfo<Store> comboStore = (ComboboxRecInfo<Store>) cbstore
                .getSelectedItem();
        ComboboxRecInfo<TypeOfUse> comboTypeOfUse = (ComboboxRecInfo<TypeOfUse>) cbtypeofuse
                .getSelectedItem();
        ComboboxRecInfo<TypeOfRegulation> comboTypeOfRegulation = (ComboboxRecInfo<TypeOfRegulation>) cbtypeofregulation
                .getSelectedItem();
        ComboboxRecInfo<StatusOfUse> comboStatusOfUse = (ComboboxRecInfo<StatusOfUse>) cbstatusofuse
                .getSelectedItem();
        item.setLanguage(comboLanguage.getKeyData());
        item.setAuthor(comboAuthor.getKeyData());
        item.setOwnerItem(comboOwner.getKeyData());
        item.setStore(comboStore.getKeyData());
        item.setTypeOfUse(comboTypeOfUse.getKeyData());
        item.setTypeOfRegulation(comboTypeOfRegulation.getKeyData());;
        item.setStatusOfUse(comboStatusOfUse.getKeyData());
    }

    private void clearAll() {
        txtname.setText("");
        txtVersion.setValue(0);
        txtcode.setText("");
        txtmodifiedDate.setText(new SimpleDateFormat("yyyy - MM - dd")
                .format(new java.util.Date()));
        txtnote.setText("");
        txtothercode.setText("");
        try {
            txtTotalPage.setValue(0);
            cbauthor.setSelectedIndex(0);
            cblanguage.setSelectedIndex(0);
            cbowner.setSelectedIndex(0);
            cbpublishdate.setSelectedIndex(0);
            cbstatusofuse.setSelectedIndex(0);
            cbstore.setSelectedIndex(0);
            cbtypeofregulation.setSelectedIndex(0);
            cbtypeofuse.setSelectedIndex(0);
        } catch (IllegalArgumentException ex) {
        }
        btaddnew.setText("Thêm mới");
        btdelete.setEnabled(false);
        btrefresh.setText("Làm mới");
        rbstatus.setSelected(true);
    }

    private String generateCode(String code) {
        String noSpace = code.trim();
        String[] splitNoSpace = noSpace.split(" ");
        String resultCode = "";
        try {
            for (String string : splitNoSpace) {
                resultCode = resultCode + string.charAt(0);
            }
            String author = cbauthor.getSelectedItem().toString().substring(0, 1);
            String version = txtVersion.getValue().toString();
            if (splitNoSpace.length == 2) {
                code = resultCode + "0" + author + "" + version;
            } else if (splitNoSpace.length == 1) {
                code = resultCode + "00" + author + "" + version;
            } else if (splitNoSpace.length > 2) {
                resultCode = resultCode.substring(0, 3);
                code = resultCode + "" + author + "" + version;
            }
        } catch (Exception ex) {
        }
        return code;
    }
}
